#include "udpServer.hpp"
#include <memory>
#include <fstream>
#include <signal.h>
#include <unordered_map>

using namespace std;
using namespace Server;

const std::string dictTxt = "./dict.txt";

static void Usage(string proc)
{
	cout << "\nUsage:\n\t" << proc << ": local_port\n\n";
}

// demo 1
void handleMessage(int sockfd, string clientip, uint16_t clientport, string message)
{
	// 完成serverd端的通信与业务的解耦
	// 最基础的业务逻辑
	string response_message = message;
	response_message += " [server echo]";

	// 把消息发回去
	struct sockaddr_in client;
	bzero(&client, sizeof(client));

	client.sin_family = AF_INET;
	client.sin_port = htons(clientport);
	client.sin_addr.s_addr = inet_addr(clientip.c_str());

	sendto(sockfd, response_message.c_str(), sizeof(response_message), 0,(struct sockaddr*)&client, sizeof(client));
}

int main(int argc, char *argv[])
{
	if (argc != 2)
	{
		Usage(argv[0]);
		exit(USAGE_ERR);
	}
	uint16_t port = atoi(argv[1]);
	// string ip = argv[1];

	// std::unique_ptr<udpServer> usvr(new udpServer(port, ip));
	// std::unique_ptr<udpServer> usvr(new udpServer(execCommand, port));
	std::unique_ptr<udpServer> usvr(new udpServer(handleMessage, port));

	usvr->initServer();
	usvr->start();
	return 0;
}
